package com.ldl.customize.controller.system.controller.system;


import com.ldl.customize.entity.User;
import com.ldl.customize.service.system.LoginService;
import com.ldl.customize.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 登录相关的操作
 */
@Controller
public class LoginController {

	static Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private LoginService loginService;
	/**
	* @Title: authenticateUser
	* @Description: 判断用户名密码是否正确
	* @param @param username
	* @param @param password
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping(value = "/authenticateUser/{username}/{password}", method = RequestMethod.GET)
	public @ResponseBody String authenticateUser(@PathVariable String username,
			@PathVariable String password) {
		return loginService.authenticateUser(username, password);
	}
	/**
	* @Title: registUser
	* @Description: 用户注册
	* @param @param user
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping(value = "/registUser", method = RequestMethod.POST)
	public @ResponseBody String registUser(@RequestBody User user) {
		String usernameString = user.getUserName();
		String emailString = user.getUserEmail();
		try{
			//查询用户名是否被注册
			if( loginService.checkName(usernameString)){
				//已注册
				return "2";
			}else if(loginService.checkEmail(emailString)){
				//已注册
				return "3";
			}
			loginService.saveUser(user);

		}catch(Exception e){
			//未知错误，注册失败
			return "1";
		}
		//注册成功
		return "0";
	}

	/**
	* @Title: login
	* @Description: 用户登录
	* @param @param username
	* @param @param model
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping(value = "/index", method = RequestMethod.POST)
	public String login(@ModelAttribute User user,Model model,HttpServletRequest request){
		logger.debug(user.getUserName());
		HttpSession session = request.getSession();
		session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());
		model.addAttribute("username", user.getUserName());
		return "index";
	}
}
